<template>
  <!-- 待办审批 -->
  <div class="wrapper">
    <div class="title">
      待办
    </div>
    <title-name :title="processName + '-' + taskName" />
    <a-card
      :body-style="{ padding: '24px 32px' }"
      :bordered="false"
    >
      <template>
        <title-name title="节点信息" />
        <a-descriptions
          class="mb20"
          title=""
        >
          <a-descriptions-item label="当前节点">
            {{ taskName }}
          </a-descriptions-item>
          <a-descriptions-item label="审批人">
            {{ currentUser.name }}
          </a-descriptions-item>
          <a-descriptions-item label="审批时间">
            {{ currentTime }}
          </a-descriptions-item>
        </a-descriptions>
      </template>
      <a-form-model
        ref="ruleForm"
        :model="form"
        :label-col="{ span: 6 }"
        :wrapper-col="{ span: 18 }"
        :rules="rules"
      >
        <!-- 表格 -->
        <title-name title="工作要求" />
        <custom-form
          :form-list="formList"
          :form="form"
          edit-model="E"
        >
          <!-- 责任人 -->
          <template #personLiable>
            <a-tag
              v-for="person in form.personLiable"
              :key="person.userId"
              class="mb12"
              :closable="false"
              color="#108ee9"
              @close="form.personLiable = form.personLiable.filter((item) => person.userId !== item.userId)"
            >
              {{ person.name }}
            </a-tag>
            <a-button
              :class="{ ml12: form.personLiable && form.personLiable.length > 0 }"
              @click="
                formName = 'personLiable'
                visible = true
              "
            >
              添加人员
            </a-button>
          </template>
          <!-- 抄送人 -->
          <template #personCC>
            <a-tag
              v-for="person in form.personCC"
              :key="person.userId"
              class="mb12"
              :closable="true"
              color="#108ee9"
              @close="form.personCC = form.personCC.filter((item) => person.userId !== item.userId)"
            >
              {{ person.name }}
            </a-tag>
            <a-button
              :class="{ ml12: form.personCC && form.personCC.length > 0 }"
              @click="
                formName = 'personCC'
                visible = true
              "
            >
              添加人员
            </a-button>
          </template>
        </custom-form>
        <!-- 页脚操作栏 -->
        <div class="btn_box">
          <a-button
            class="button_right"
            @click="$close"
          >
            关闭
          </a-button>
          <a-button
            :loading="loading"
            type="primary"
            @click="handelApproval"
          >
            提交
          </a-button>
        </div>
      </a-form-model>
    </a-card>
    <a-card>
      <h1 class="mb20">
        风险管理信息详情
      </h1>
      <a-card>
        <title-name title="风险详情" />
        <a-spin :spinning="spinning">
          <custom-form
            :form-list="baseInfo"
            :form="formInfo"
            is-validate
          >
            <template #riskLevel>
              <a-radio-group
                v-model="formInfo.riskLevel"
                style="width: 100%"
              >
                <div class="mb12">
                  <a-radio
                    :value="1"
                    :disabled="formInfo.riskLevel !== 1"
                  >
                    一般风险
                  </a-radio>
                  {{ formInfo.generalRisk }}
                </div>
                <div class="mb12">
                  <a-radio
                    :value="2"
                    :disabled="formInfo.riskLevel !== 2"
                  >
                    较大风险
                  </a-radio>
                  {{ formInfo.greaterRisk }}
                </div>
                <div class="mb12">
                  <a-radio
                    :value="3"
                    :disabled="formInfo.riskLevel !== 3"
                  >
                    重大风险
                  </a-radio>
                  {{ formInfo.majorRrisk }}
                </div>
              </a-radio-group>
            </template>
          </custom-form>
        </a-spin>
      </a-card>
    </a-card>
    <!-- 人员选择 -->
    <SelectPersonModal
      :is-mutilple="formName === 'personCC'"
      :persons="form[formName]"
      :visible.sync="visible"
      :need-tree="false"
      :form="args"
      :before-init="queryParams"
      @confirmSelect="visible = false"
    />
  </div>
</template>

<script>
import { completeTask } from '@/api/process'
import moment from 'moment'
import Vue from 'vue'
import { notifyParentWindow } from '@/utils/util.js'
import riskListApi from '@/api/legal/risk/list'
import SelectPersonModal from '@/components/SelectPersonModal' // 人员
import { getDept } from '@/api/commons'

export default {
  name: 'RiskAudit',
  components: {
    SelectPersonModal
  },
  data() {
    return {
      form: {
        personLiable: [],
        personCC: [],
        orgSelectedName: '',
        orgSelectedLabel: '',
        jobsSelectedName: undefined, //岗位
        respEmployeeId: undefined //人员
      },
      baseInfo: [
        {
          keyName: 'branchCompanyproject',
          label: '所属分公司'
        },
        // {
        //   keyName: 'branchCompany',
        //   label: '所属分公司'
        // },
        // {
        //   keyName: 'project',
        //   label: '项目名称'
        // },
        {
          keyName: 'form1.haveRiskFactors',
          label: '是否风险要素库风险',
          customRender() {
            return arguments[0] ? '是' : '否'
          }
        },
        {
          keyName: 'riskName',
          label: '风险名称'
        },
        {
          keyName: 'orgName',
          label: '责任部门'
        },
        {
          keyName: 'riskContent',
          label: '风险描述'
        },
        {
          keyName: 'riskLevel',
          label: '风险级别',
          slot: true,
          span: 24
        },
        {
          keyName: 'creatorName',
          label: '创建人'
        },
        {
          keyName: 'createTime',
          label: '创建时间'
          // customRender: () => {
          //   return this.formInfo.createTime ? this.$dateFormat(this.formInfo.createTime, 'D') : '无'
          // }
        }
      ],
      formName: '', // 添加人员绑定字段
      formInfo: {}, // 风险基础信息
      visible: false,
      rules: {
        personCC: [{ type: 'array', required: true, message: '请选择抄送人员', trigger: 'change' }],
        personLiable: [{ type: 'array', required: true, message: '请选择责任人', trigger: 'change' }],
        workContent: [{ required: true, whitespace: true, message: '请输入工作要求', trigger: 'change' }],
        processingTime: [{ required: true, message: '请选择处理时限', trigger: 'change' }]
      }, // 校验规则
      loading: false,
      opinions: '',
      approveInfos: [], // 审批流程信息
      procInstId: '', //当前流程实例ID
      taskId: '', //当前流程节点ID
      processName: '', //流程名称
      taskName: '', //当前流程节点名称
      taskDefKey: '', //任务标识
      currentTime: '', //当前审批时间
      currentUser: '', //当前审批人
      flowRequesting: false,
      detailUrl: null, //详情地址
      spinning: false,
      assignType: '', //节点类型   0 变量获取 1 处理人 2 候选人 3 候选组 4 会签
      assignCode: '', //候选组编码 岗位编码
      assignLevel: '', //层级 项目部 PD 分公司 BC 公司 CO
      businessType: '', //业务类型 0 项目
      args: {} // 添加人员请求参数
    }
  },
  computed: {
    // 表单列表配置项
    formList() {
      return [
        {
          keyName: 'personLiable',
          label: '责任人',
          slot: true,
          span: 12
        },
        {
          keyName: 'processingTime',
          type: 'a-date-picker',
          placeholder: '请选择日期',
          label: '处理时限',
          span: 12,
          attrs: {
            valueFormat: 'YYYY-MM-DD'
          }
        },
        {
          keyName: 'workContent',
          type: 'BaseTextarea',
          label: '工作要求',
          span: 24,
          attrs: {
            maxLength: 500
          }
        },
        {
          keyName: 'personCC',
          label: '抄送人',
          slot: true,
          span: 24
        }
      ]
    }
  },
  created() {
    const {
      type,
      code,
      level,
      btype,
      businessId,
      procInstId,
      name,
      processName,
      detailUrl,
      taskId,
      taskDefKey
    } = this.$route.query
    if (type) {
      this.assignType = type
      this.assignCode = code
      this.assignLevel = level
      this.businessType = btype
    }
    this.id = businessId
    if (!this.id) {
      this.$error({ content: '无指定业务ID，将自动关闭' })
      setTimeout(() => {
        window.close()
      }, 1500)
      return
    }
    this.procInstId = procInstId
    this.taskName = decodeURIComponent(name)
    this.processName = decodeURIComponent(processName)
    document.title = this.processName + '-' + this.taskName
    if (detailUrl) {
      this.detailUrl = decodeURIComponent(detailUrl)
    }
    this.taskId = taskId
    this.taskDefKey = taskDefKey
    this.currentTime = moment().format('YYYY-MM-DD HH:mm:ss')
    this.currentUser = Vue.getAcloudProvider().getUserInfo()
    this.getBaseInfo()
  },
  methods: {
    /**
     * @description: 添加人员请求参数
     * @return {Object}
     */
    queryParams() {
      if (this.formName === 'personLiable') {
        let code = this.$userType()
        // 若处理人为公司级，人员选择范围为西南公司所有人、该风险所在项目部或风险所在项目部的上级分公司的所有人
        if (code === 'CO') {
          return getDept({
            id: `${this.$currentPost().id},${this.formInfo.branchCompanyId},${this.formInfo.projectOrgId}`,
            type: 2
          }).then((res) => {
            if (res?.data?.length > 0) {
              let rootOrgIds = res.data.map((item) => item.id)
              this.args = { rootOrgIds }
              return true
            }
          })
          // 若处理人为分公司级，人员选择范围为本分公司所有人、该风险所在项目部所有人
        } else if (code === 'BC') {
          return getDept({
            id: `${this.$currentPost().id},${this.formInfo.projectOrgId}`,
            type: 2
          }).then((res) => {
            if (res?.data?.length > 0) {
              let rootOrgIds = res.data.map((item) => item.id)
              this.args = { rootOrgIds }
              return true
            }
          })
          // 若处理人为项目部，人员选择范围为项目部的所有人
        } else if (code === 'PD') {
          this.args = { rootOrgId: this.$currentPost().id }
          return Promise.resolve(true)
        }
      } else {
        this.args = {}
        return Promise.resolve(true)
      }
    },
    /**
     * @description: 获取风险基本信息
     */
    async getBaseInfo() {
      this.spinning = true
      let res = await riskListApi.findListByMainId({}, { id: this.id })
      if (res.code === this.SUCCESS_CODE && res.data) {
        this.formInfo = res.data;
        this.formInfo.branchCompanyproject = this.formInfo.branchCompany + '/' + this.formInfo.project
      }
      this.spinning = false
    },
    /**
     * @description: 完成审批
     * @param {*} reject 是否拒绝
     * @return {*}
     */
    submit(reject) {
      const data = {
        formData: {
          opinions: this.opinions,
          reject,
          projectId: ''
        },
        assignTypeEnum: this.assignType, //指派类型
        assgins: this.form.respEmployeeId, //人员
        groupEnum: this.form.jobsSelectedName, //岗位
        procInstId: this.procInstId,
        taskId: this.taskId,
        userId: this.currentUser.id
      }
      const variable = {}
      // return;
      if (reject) {
        variable.reject = true
      }

      data.variables = {
        ...variable,
        ...this.submitData // 特殊流程的数据，转交给审批
      }

      return completeTask(data)
        .then((res) => {
          if (res.status === 200) {
            notifyParentWindow() // 通知父窗口
            // this.$success({
            //   content: '审批提交成功，即将自动关闭当前窗口',
            //   onOk() {
                window.close()
            //   }
            // })
            // setTimeout(() => {
            //   window.close()
            // }, 2000)
          } else {
            this.$error({ content: '审批提交失败，请稍后重试' })
          }
          return res
        })
        .catch((err) => {
          return err
        })
    },
    /**
     * @description: 提交工作要求
     */
    handelApproval() {
      // 审批通过
      this.$refs.ruleForm.validate((e) => {
        if (e) {
          this.$confirm({
            title: '提示',
            content: '请确认是否要提交，提交后不可再次修改',
            onOk: async () => {
              let form = this.$clone(this.form)
              // 格式化抄送人
              form.personCC = form.personCC?.map((item) => item.userId).join()
              // 格式化责任人
              form.personLiable = form.personLiable?.map((item) => item.userId).join()
              // 添加业务id
              form.id = this.id
              let res = await riskListApi.editByRiskApply(form)
              return res.code === this.SUCCESS_CODE
                ? Promise.all([
                    this.submit(false)
                      .then(() => {
                        resolve()
                        confirmWin.destroy()
                      })
                      .catch(() => reject)
                  ])
                : Promise.reject()
            }
          })
        }else {
          this.$message.warning("请填写完所有必填项信息")
        }
      })
    }
  }
}
</script>

<style lang="less" scoped>
.img-wrapper {
  padding: 10px 0;
}
.wrapper {
  padding: 20px;

  .title {
    font-size: 20px;
    font-weight: bold;
    margin-bottom: 20px;
  }

  /deep/ .approval-item .ant-form-item-control-wrapper {
    width: 100%;
  }
}

.wrapper-row {
  padding-left: 55px;
  font-weight: bold;
  letter-spacing: 1px;
}

/deep/ .ant-form-item label {
  font-size: 12px;
}

/deep/ .ant-btn {
  border-radius: 5px;
}

/deep/ .ant-input {
  /*width: 70%;*/
  border-radius: 5px;
}

/deep/ .ant-card.ant-card-bordered {
  border-radius: 5px;
}

.ant-avatar-lg {
  width: 48px;
  height: 48px;
  line-height: 48px;
}

.list-content-item {
  color: rgba(0, 0, 0, 0.45);
  display: inline-block;
  vertical-align: middle;
  font-size: 14px;
  margin-left: 40px;

  span {
    line-height: 20px;
  }

  p {
    margin-top: 4px;
    margin-bottom: 0;
    line-height: 22px;
  }
}

.title-name {
  border-left: 5px solid #1890ff;
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 20px;
  padding-left: 15px;
  height: 20px;
  line-height: 20px;
}

/deep/ .table-page-search-wrapper .ant-form-inline .ant-row .ant-col.ant-col-sm-24.ant-col-md-12 {
  padding-left: 80px;
}

/deep/ .col .ant-form-item .ant-form-item-control-wrapper {
  width: calc(100% - 135px);
}
/deep/ .BaseTextarea-container .ant-input {
  border-color: #e4ac0b;
  background-color: #fff9e8;
}
</style>

